package com.phy.core;

import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletException;
import javax.servlet.FilterConfig;

/**
 * Servlet implementation class EncodingFilter
 */
public class EncodingFilter implements Filter {
	private static final long serialVersionUID = 1L;

	protected FilterConfig filterConfig;
    private String targetEncoding = "utf-8";
    
    /**
     *初始化过滤器,和一般的Servlet一样，它也可以获得初始参数。
     */
    public void init(FilterConfig config) throws ServletException {
        this.filterConfig = config;
        this.targetEncoding = config.getInitParameter("encoding");
    }
    
    /**
      *进行过滤处理，这个方法最重要，所有过滤处理的代码都在此实现。
      */
     public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain chain)
        throws IOException, ServletException {
    	 srequest.setCharacterEncoding("utf-8");//设置服务器请求的统一编码
    	 sresponse.setCharacterEncoding("utf-8");//设置服务器响应的统一编码
       //  System.out.println("使用以下方法对请求进行编码：encoding="+targetEncoding);
        HttpServletRequest request = (HttpServletRequest)srequest;
        request.setCharacterEncoding(targetEncoding);
        // 把处理权发送到下一个
       chain.doFilter(srequest,sresponse); 
    }

public void setFilterConfig(final FilterConfig filterConfig)
{
   this.filterConfig=filterConfig;
}
    
    //销毁过滤器
public void destroy()
{
   this.filterConfig=null;
}

}
